#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cstring>
#include <cmath>

using namespace std;

#include "EasyBMP.h"
#include "Matrix.h"

char* CreateFilename( const char* base , double time )
{
 char* Output = NULL;
 Output = new char [1024];
 sprintf( Output , "%s_%3.8f.dat" , base , time );
 
 int hits = 0;
 int i=0; 
 while( hits < 1 && i < strlen(Output) )
 {
  if( Output[i] == '.' )
  { Output[i] = '_'; hits++; }
  i++;
 } 
 
 return Output;
}

RGBApixel OrderedTripleToRGBApixel( char* Triple )
{
 RGBApixel Output;
 Output.Red = 255;
 Output.Green = 255;
 Output.Blue = 255;
 int i=0;
 int k=0;
 
 // find the red position
 
 while( !isdigit( Triple[i] ) )
 { i++; }
 int RedStart = i;
 while( isdigit( Triple[i] ) )
 { i++; }
 int RedEnd = i-1;
 
 // extract red
 
 char Temp [3];
 for( int j=0; j < 3 ; j++ )
 { Temp[j] = '\0'; } 
 k=0;
 for( int j=RedStart ; j <= RedEnd ; j++ )
 { Temp[k] = Triple[j]; k++; }
 Output.Red = (ebmpBYTE) atoi( Temp );
 
 // find the green position
 
 while( !isdigit( Triple[i] ) )
 { i++; }
 int GreenStart = i;
 while( isdigit( Triple[i] ) )
 { i++; }
 int GreenEnd = i-1;
 
 // extract green
 
 for( int j=0; j < 3 ; j++ )
 { Temp[j] = '\0'; } 
 k=0;
 for( int j=GreenStart ; j <= GreenEnd ; j++ )
 { Temp[k] = Triple[j]; k++; }
 Output.Green= (ebmpBYTE) atoi( Temp );

 // find the blue position
 
 while( !isdigit( Triple[i] ) )
 { i++; }
 int BlueStart = i;
 while( isdigit( Triple[i] ) )
 { i++; }
 int BlueEnd = i-1;

 // extract blue
 
 for( int j=0; j < 3 ; j++ )
 { Temp[j] = '\0'; } 
 k=0;
 for( int j=BlueStart ; j <= BlueEnd ; j++ )
 { Temp[k] = Triple[j]; k++; }
 Output.Blue = (ebmpBYTE) atoi( Temp );
 return Output; 
}

void DisplayColor( RGBApixel Color )
{
 cout << " ( " << (int) Color.Red  << " , " 
      <<          (int) Color.Green << " , " 
      <<     	  (int) Color.Blue  << " ) " << endl;
 return;
}

bool SetGlobalColors( void )
{
 extern RGBApixel Black;
 Black.Red = 0;
 Black.Green = 0;
 Black.Blue = 0;
 extern RGBApixel White;
 White.Red = 255;
 White.Green =255;
 White.Blue = 255;

 return true;
}

bool FindMinAndMax( Matrix& Input, double* min, double* max )
{
 *min = 9e9;
 *max = -9e9;
 
 for( int i=0; i < Input.TellRows() ; i++ )
 {
  for( int j=0 ; j < Input.TellCols() ; j++ )
  {
   double val = *Input(i,j);
   if( val < *min )
   { *min = val; }
   if( val > *max )
   { *max = val; }
  }
 }
 return true;
}

bool FindVesselMinAndMax( Matrix& Input, Matrix& VesselIndicator, double* min, double* max )
{

 *min = 9e9;
 *max = -9e9;
 
 for( int i=0; i < Input.TellRows() ; i++ )
 {
  for( int j=0 ; j < Input.TellCols() ; j++ )
  {
   if( *VesselIndicator(i,j) > 0.05 )
   {
    double val = *Input(i,j);
    if( val < *min )
    { *min = val; }
    if( val > *max )
    { *max = val; }
   }
  }
 }
 return true;
}
